<template>
  <div class="addExpense">
    <el-form ref="form" :model="form" :rules="roleCodeRule" label-width="120px">
      <el-row>
        <mainTilte title="基本信息" />
      </el-row>
      <el-row>
        <el-col :span="10">
          <el-form-item label="提单号" prop="bl_no">
            <app-select v-model="form.bl_no" url="/transhipment-order" :params="blnoParams" options-label="bl_no" options-value="bl_no" placeholder="请选择提单号" @change="handleSelect" />
          </el-form-item>
        </el-col>

        <el-col :span="10">
          <el-form-item label="付款抬头" prop="pay_title">
            <app-select v-model="form.pay_title" url="/company" :params="titleParams" options-label="name" options-value="name" placeholder="请选择付款抬头" />
          </el-form-item>
        </el-col>
      </el-row>
      <egrid
        v-loading="loading"
        class="egrid mb24"
        stripe
        fit
        border
        highlight-current-row
        element-loading-text="正在努力加载中..."
        :data="tableData"
        :columns="addExpencolumns"
        :columns-schema="addExpencolumnsSchema"
        :columns-handler="addExpencolumnsHandler"
        @selection-change="checkIds"
      />
      <el-row>
        <mainTilte title="国内路运费用(工厂--->出发港)" />
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="货代" prop="domestic_trans.lforwarder_id">
            <el-select v-model.trim="form.domestic_trans.lforwarder_id" clearable placeholder="货代" @change="changeLforwarderCompanyHandler($event, 'domestic_trans')" @input="inputChange">
              <el-option v-for="item of freightList" :key="item.id" :label="item.name" :value="item.id" :disabled="item.disable" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="拖车费" prop="domestic_trans.traile_fee">
            <el-input-number v-model.trim="form.domestic_trans.traile_fee" :controls="false" controls-position="right" :precision="2" class="wfull tal" :min="0" :max="9999999999.99" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="绕路费" prop="domestic_trans.detour_fee">
            <el-input-number v-model.trim="form.domestic_trans.detour_fee" :controls="false" controls-position="right" :precision="2" class="wfull tal" :min="0" :max="9999999999.99" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="提进费" prop="domestic_trans.advance_fee">
            <el-input-number v-model.trim="form.domestic_trans.advance_fee" :controls="false" controls-position="right" :precision="2" class="wfull tal" :min="0" :max="9999999999.99" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="报关费" prop="domestic_trans.declare_fee">
            <el-input-number v-model.trim="form.domestic_trans.declare_fee" :controls="false" controls-position="right" :precision="2" class="wfull tal" :min="0" :max="9999999999.99" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="合计">
            <el-input v-model.trim="domesticAmount" disabled />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <mainTilte title="海运费用(出发港----->目的港)" />
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="货代" prop="ocean_shipping.lforwarder_id">
            <el-select v-model.trim="form.ocean_shipping.lforwarder_id" clearable placeholder="货代" @change="changeLforwarderCompanyHandler($event, 'ocean_shipping')" @input="">
              <el-option v-for="item of freightList" :key="item.id" :label="item.name" :value="item.id" :disabled="item.disable" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="类型" prop="ocean_shipping.type">
            <el-select v-model.trim="form.ocean_shipping.type" clearable placeholder="类型">
              <el-option v-for="(item, index) of typeList" :key="index" :label="item.dict_data_name" :value="`${item.id}`" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="海运费(USD)" prop="ocean_shipping.fee">
            <el-input-number v-model.trim="form.ocean_shipping.fee" :controls="false" controls-position="right" :precision="2" class="wfull tal" :min="0" :max="9999999999.99" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="税金(USD)" prop="ocean_shipping.tax_fee">
            <el-input-number v-model.trim="form.ocean_shipping.tax_fee" :controls="false" controls-position="right" :precision="2" class="wfull tal" :min="0" :max="9999999999.99" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="总美金费用（USD）">
            <el-input v-model.trim="oceanUsd" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="人民币费用(RMB)">
            <el-input v-model.trim="form.ocean_shipping.amount_rmb" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="合计(RMB)">
            <el-input v-model.trim="oceanAmount" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="备注" prop="ocean_shipping.notes">
            <el-input v-model="form.ocean_shipping.notes" type="textarea" autosize />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <mainTilte title="国外路运费用(目的港----->实体仓)" />
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="货代" prop="overseas_trans.lforwarder_id">
            <el-select v-model.trim="form.overseas_trans.lforwarder_id" clearable placeholder="货代" @change="changeLforwarderCompanyHandler($event, 'overseas_trans')">
              <el-option v-for="item of freightList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="其他费用" prop="overseas_trans.other_fee">
            <el-input-number v-model.trim="form.overseas_trans.other_fee" :controls="false" controls-position="right" :precision="2" class="wfull tal" :min="0" :max="9999999999.99" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="合计">
            <el-input v-model.trim="form.overseas_trans.other_fee" disabled />
          </el-form-item>
        </el-col>
      </el-row>
      <div class="dialog-footer-center">
        <span>
          <el-button :loading="canSaveLoading" type="primary" @click="onSubmit">保存</el-button>
          <el-button @click="$router.push('/supplyChain/expenseList')">取消</el-button>
        </span>
      </div>
    </el-form>
  </div>
</template>

<script>
import list from '@/layout/mixin/list'
export default {
  name: 'PurchaseExpenseAdd',
  mixins: [list],
  data() {
    return {
      canSaveLoading: false,
      loading: false,
      form: {
        bl_no: '',
        pay_title: '',
        domestic_trans: {
          // 国内陆运
          lforwarder_company: '', // 货代公司
          lforwarder_id: '',
          traile_fee: undefined, // 拖车费
          detour_fee: undefined, // 绕路费
          advance_fee: undefined, // 提进费
          declare_fee: undefined, // 报关费
          amount: '' // 总计
        },
        ocean_shipping: {
          // 海运
          lforwarder_company: '', // 货代公司
          lforwarder_id: '',
          type: '', // 类型
          fee: undefined, // 海运费
          tax_fee: undefined, // 税金
          amount_usd: '', // 总美金费用
          amount_rmb: '0', // 人民币费用
          notes: '', // 备注
          amount: '' // 合计
        },
        overseas_trans: {
          lforwarder_company: '', // 货代公司
          lforwarder_id: '',
          other_fee: undefined, // 其他费用
          amount: '' // 总计
        }
      },
      roleCodeRule: {
        bl_no: [{ required: true, message: '请输入提单号', trigger: 'change' }],
        pay_title: [
          { required: true, message: '请输入付款抬头', trigger: 'blur' }
        ],
        'domestic_trans.lforwarder_id': [
          { required: true, message: '请选择货代', trigger: 'change' }
        ],
        'domestic_trans.traile_fee': [
          { required: true, message: '请输入拖车费', trigger: 'blur' }
        ],
        'domestic_trans.detour_fee': [
          { required: true, message: '请输入绕路费', trigger: 'blur' }
        ],
        'domestic_trans.advance_fee': [
          { required: true, message: '请输入提进费', trigger: 'blur' }
        ],
        'domestic_trans.declare_fee': [
          { required: true, message: '请输入报关费', trigger: 'blur' }
        ],
        'ocean_shipping.lforwarder_id': [
          { required: true, message: '请选择货代', trigger: 'change' }
        ],
        'ocean_shipping.type': [
          { required: true, message: '请选择类型', trigger: 'change' }
        ],
        'ocean_shipping.fee': [
          { required: true, message: '请输入海运费(USD)', trigger: 'blur' }
        ],
        'ocean_shipping.tax_fee': [
          { required: true, message: '请输入税金(USD)', trigger: 'blur' }
        ],
        'ocean_shipping.amount_rmb': [
          { required: true, message: '请输入人民币费用(RMB)', trigger: 'blur' }
        ],
        'overseas_trans.lforwarder_id': [
          { required: true, message: '请选择货代', trigger: 'change' }
        ],
        'overseas_trans.other_fee': [
          { required: true, message: '请输入其他费用', trigger: 'blur' }
        ]
      },
      blnoList: [],
      payList: [],
      addExpencolumns: [
        {
          label: '柜号',
          prop: 'cabinet_no',
          align: 'center',
          tooltip: false
        },
        {
          label: '装柜日期',
          prop: 'loading_date',
          align: 'center',
          tooltip: false
        },
        {
          label: 'ETD',
          prop: 'shipment_date',
          align: 'center',
          tooltip: false
        },
        {
          label: '出运单号',
          prop: 'code',
          align: 'center',
          tooltip: false
        },
        {
          label: '目的港',
          prop: 'destination_port_text',
          align: 'center',
          tooltip: false
        }
      ],
      /** *
       * 字典表组件
       */
      addExpencolumnsSchema: {},
      freightList: [],
      typeList: [],
      timeoutNo: null,
      timeoutPay: null,
      tableData: [],
      blNoList: [],
      isEdit: false,
      blnoParams: {
        page: 1,
        limit: 100000000,
        audit_status: 1,
        is_bill: 1
      },
      titleParams: {
        page: 1,
        limit: 100000000,
        is_status: 1
      },
      USDCurrency: {}
    }
  },
  computed: {
    // 国内陆运-合计
    domesticAmount() {
      const { traile_fee, detour_fee, advance_fee, declare_fee } = this.form.domestic_trans
      const sum = this.$computed.accAdd(traile_fee, detour_fee)
      const sum1 = this.$computed.accAdd(sum, advance_fee)
      const sum2 = this.$computed.accAdd(sum1, declare_fee)
      return sum2
    },
    // 海运-总美金费用（USD）
    oceanUsd() {
      return this.$computed.accAdd(this.form.ocean_shipping.fee, this.form.ocean_shipping.tax_fee)
    },
    // 海运-合计（人民币费用(RMB)）
    oceanAmount() {
      const USD_COUNT = this.USDCurrency.rate ? this.$computed.accMul(this.oceanUsd, this.USDCurrency.rate).toFixed(2) : 0
      return this.$computed.accAdd(USD_COUNT, this.form.ocean_shipping.amount_rmb)
    }
  },
  created() {
    this.getFreightList()
    this.getSeaTransportList() // 海运费用类型
    this.getCurrency()
  },
  mounted() {
    if (this.$route.query && this.$route.query.row) {
      this.form = JSON.parse(this.$route.query.row)
      this.form.domestic_trans = JSON.parse(this.form.domestic_trans)
      this.form.ocean_shipping = JSON.parse(this.form.ocean_shipping)
      this.form.overseas_trans = JSON.parse(this.form.overseas_trans)
      if (this.form.bl_no) {
        this.asyncGetBlnoData(this.form.bl_no)
      }
      this.isEdit = true
    }
    this.getFreightList()
    this.getSeaTransportList() // 海运费用类型
    this.getCurrency()
  },
  methods: {
    inputChange() { this.$forceUpdate() },
    changeLforwarderCompanyHandler(id, key) {
      const vm = this
      const item = vm.freightList.find(e => e.id === id)
      vm.form[key].lforwarder_company = item.name
    },
    // 获取汇率
    getCurrency() {
      const vm = this
      const params = {
        source_code: 'USD'
        // name: '美元'
      }
      vm.$http.get('/currencyAll', { params }).then(res => {
        if (res.data.length > 0) {
          vm.USDCurrency = res.data[0]
        } else {
          vm.$message.error('USD币别不存在')
        }
      })
    },
    getSeaTransportList() {
      const vm = this
      vm.$cache.getDic('sea_transport_type').then(res => {
        vm.typeList = res
      })
    },
    // 获取货代列表
    getFreightList() {
      const vm = this
      const params = {
        page: 1,
        limit: 1000000,
        // status: 1,
        type: 2
      }
      vm.$http.get('/lforwarder', { params }).then((res) => {
        vm.freightList = res.data.map((arr) => {
          if (arr.is_status === 1) {
            arr.disable = false
          } else {
            arr.disable = true
          }
          return arr
        })
      })
    },
    addExpencolumnsHandler() { },
    // 根据提单号获取柜号等信息
    asyncGetBlnoData(queryString) {
      this.loading = true
      this.$http
        .get(`/transhipment-order?bl_no=${queryString}`)
        .then((res) => {
          if (res.code === 10000 && res.data && res.data.length > 0) {
            this.tableData = res.data.filter(e => e.bl_no === queryString)
          }
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },
    createStateFilter(queryString) {
      return (state) => {
        return (
          state.value.toLowerCase().indexOf(queryString.toLowerCase()) !== -1
        )
      }
    },
    handleSelect() {
      this.asyncGetBlnoData(this.form.bl_no)
      this.tableData = this.blNoList
    },
    handleSelectPay(item) { },
    onSubmit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.canSaveLoading = true
          this.form.domestic_trans.amount = this.domesticAmount
          this.form.ocean_shipping.amount_usd = this.oceanUsd
          // this.form.ocean_shipping.amount_rmb = this.oceanAmount
          this.form.ocean_shipping.amount = this.oceanAmount
          this.form.overseas_trans.amount = this.form.overseas_trans.other_fee
          delete this.form.updated_at
          delete this.form.created_at
          if (this.isEdit) {
            this.$http
              .put(`/utilitybill/${this.form.id}`, this.form)
              .then((res) => {
                if (res.code === 10000) {
                  this.$message.success('修改成功')
                }
                this.canSaveLoading = false
                this.$router.push('/supplyChain/expenseList')
              })
              .catch(() => {
                this.loading = false
                this.canSaveLoading = false
              })
          } else {
            this.$http
              .post(`/utilitybill`, this.form)
              .then((res) => {
                if (res.code === 10000) {
                  this.$message.success('新增成功')
                }
                this.canSaveLoading = false
                this.$router.push('/supplyChain/expenseList')
              })
              .catch((err) => {
                console.log(err)
                this.canSaveLoading = false
              })
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.addExpense {
  padding: 15px;
  background: #fff;
}
.addExpense /deep/.el-select,
.el-autocomplete {
  width: 100%;
}
.addExpense ::v-deep .el-input-number.is-without-controls .el-input__inner {
  text-align: left;
}
</style>
